/**
 * @author gao
 * @date 2025/7/20 22:24
 */

// 为了简单，这里不加泛型参数
// 假定初始元素类型为String
class MyBlockingQueue {

    // 利用数组实现
    private String[] array = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    private Object locker1 = new Object();
    public MyBlockingQueue(int capacity) {
        array = new String[capacity];
    }

    /**
     *
     * @param elem 入队列
     */
    public void put(String elem) throws InterruptedException {
        synchronized (locker1) {
            if (size >= array.length) {
                locker1.wait();
            }
            array[tail] = elem;
            tail++;
            if (tail >= array.length) {
                tail = 0;
            }
            size++;
            locker1.notify();
        }
    }

    /**
     *
     * @return 获取队列元素
     */
    public String take() throws InterruptedException {
        synchronized (locker1) {
            if (size == 0) {
                locker1.wait();
            }
            String ret = array[head];
            head++;
            if (head >= array.length) {
                head = 0;
            }
            size--;
            // 唤醒put方法里的阻塞
            locker1.notify();
            return ret;
        }
    }
}

public class Demo3 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread producer = new Thread(() -> {
            int count = 0;
            while (true) {
                try {
                    queue.put("" + count);
                    System.out.println("生产了一个元素：" + count);
                    count++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            while (true) {
                try {
                    String elem = queue.take();
                    System.out.println("消费了一个元素：" + elem);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}